#!/bin/bash
#需要一台有外网的机器上操作
#需要先上传镜像iso到/mnt
#后续有新rpm包可下载到cd /usr/local/nginx/html/yum-repo/rocky9/x86_64/extra，比如repotrack vim
#执行createrepo /usr/local/nginx/html/yum-repo/rocky9/x86_64/extra，刷新元数据

set -e  # 脚本执行出错立即退出

# ===================== 配置参数（可根据需求修改）=====================
NGINX_VERSION="1.24.0"          # Nginx 版本
NGINX_INSTALL_PATH="/usr/local/nginx"  # Nginx 安装路径
REPO_ROOT="/usr/local/nginx/html/yum-repo/rocky9/x86_64"  # YUM 仓库根目录
SERVER_IP=$(hostname -I | awk '{print $1}')  # 自动获取服务器 IP（默认第一个网卡 IP）
DOWNLOAD_PACKAGES="vim"  # 要下载的 RPM 包（可新增）
ISO_FILES="/mnt/Rocky-9.6-x86_64-dvd.iso"
# ===================== 第一步：安装依赖工具 =====================
echo -e "\n[1/5] 安装编译 Nginx 和 YUM 仓库所需依赖..."
if [ -f "$ISO_FILES" ]; then
    mkdir -p /mnt/iso && mount -o loop $ISO_FILES /mnt/iso && echo "挂载成功！"
else
    echo "上传镜像/mnt/并且mount -o loop /mnt/*.iso /mnt/iso"; exit 1
fi

if [ -d /mnt/iso/BaseOS ];then
  dnf install -y wget tar gcc gcc-c++ make openssl-devel pcre-devel zlib-devel yum-utils createrepo || { echo "依赖安装失败！"; exit 1; } #用的阿里yum源
else
    echo "需要mkdir /mnt/iso并挂载rocky9镜像至/mnt/iso！"; exit 1
fi

# ===================== 第二步：二进制编译安装 Nginx =====================
echo -e "\n[2/5] 编译安装 Nginx $NGINX_VERSION..."
# 创建下载目录
mkdir -p /usr/local/src/nginx
cd /usr/local/src/nginx || exit 1

# 下载 Nginx 源码包（失败则重试 3 次）
if [ ! -f "nginx-$NGINX_VERSION.tar.gz" ]; then
    wget --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 -t 3 https://nginx.org/download/nginx-$NGINX_VERSION.tar.gz || { echo "Nginx 源码包下载失败！"; exit 1; }
fi

# 解压并编译
tar zxf nginx-$NGINX_VERSION.tar.gz
cd nginx-$NGINX_VERSION || exit 1

./configure \
--prefix=$NGINX_INSTALL_PATH \
--with-http_stub_status_module \
--with-http_ssl_module \
--without-http_gzip_module

make && make install || { echo "Nginx 编译安装失败！"; exit 1; }

# 配置 systemd 服务
cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=Nginx HTTP Server
After=network.target

[Service]
Type=forking
ExecStart=$NGINX_INSTALL_PATH/sbin/nginx
ExecReload=$NGINX_INSTALL_PATH/sbin/nginx -s reload
ExecStop=$NGINX_INSTALL_PATH/sbin/nginx -s stop
PrivateTmp=true

[Install]
WantedBy=multi-user.target
EOF

# 启动 Nginx 并设置开机自启
systemctl daemon-reload
systemctl start nginx || { echo "Nginx 启动失败！"; exit 1; }
systemctl enable nginx

# 验证 Nginx 运行状态
if systemctl is-active --quiet nginx; then
    echo "Nginx 安装并启动成功！"
else
    echo "Nginx 启动失败！"; exit 1
fi

# ===================== 第三步：创建 YUM 仓库目录结构 =====================
echo -e "\n[3/5] 创建 YUM 仓库目录结构..."
mkdir -p $REPO_ROOT/base $REPO_ROOT/app $REPO_ROOT/extra || { echo "仓库目录创建失败！"; exit 1; }
#chown -R nginx:nginx $NGINX_INSTALL_PATH/html/yum-repo || { echo "目录权限设置失败！"; exit 1; }

# ===================== 第四步：用 repotrack 下载 RPM 包及依赖 =====================
echo -e "\n[4/5] 下载指定 RPM 包及依赖（可能需要几分钟，取决于网络）..."
#cd $REPO_ROOT/extra #有外网可加
#repotrack $DOWNLOAD_PACKAGES || { echo "RPM 包下载失败！请检查外网连接"; exit 1; }
if [ -d /mnt/iso/BaseOS ];then
cp -r /mnt/iso/BaseOS/*  $REPO_ROOT/base
else
    echo "需要挂载镜像至/mnt/iso！"; exit 1
fi

if [ -d /mnt/iso/AppStream ];then
cp -r /mnt/iso/AppStream/*  $REPO_ROOT/app
else
    echo "需要挂载镜像至/mnt/iso！"; exit 1
fi

# 生成 YUM 仓库元数据
echo -e "\n生成仓库元数据..."
createrepo $REPO_ROOT/base || { echo "元数据生成失败！"; exit 1; }
createrepo $REPO_ROOT/app || { echo "元数据生成失败！"; exit 1; }
createrepo $REPO_ROOT/extra || true  # extra 目录暂时为空，元数据生成不报错

# ===================== 第五步：配置 Nginx 允许目录浏览 =====================
echo -e "\n[5/5] 配置 Nginx 仓库访问..."
# 备份原 Nginx 配置文件
cp $NGINX_INSTALL_PATH/conf/nginx.conf $NGINX_INSTALL_PATH/conf/nginx.conf.bak

# 替换 Nginx 配置（添加仓库目录浏览）
cat > $NGINX_INSTALL_PATH/conf/nginx.conf << EOF
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       80;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
        }

        # YUM 仓库目录配置
        location /yum-repo/ {
            root   html;
            autoindex on;
            autoindex_exact_size off;
            autoindex_localtime on;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}
EOF

# 重启 Nginx 使配置生效
systemctl restart nginx || { echo "Nginx 重启失败！"; exit 1; }
systemctl disable --now  firewalld

# ===================== 部署完成提示 =====================
echo -e "\n========================================"
echo "YUM 仓库搭建完成！"
echo "========================================"
echo "仓库服务器 IP：$SERVER_IP"
echo "仓库访问地址：http://$SERVER_IP/yum-repo/rocky9/x86_64/base"
echo "已下载的包：$DOWNLOAD_PACKAGES"
echo -e "\n客户端配置方法："
echo "1. 备份原有 YUM 源：mkdir -p /etc/yum.repos.d/backup && mv /etc/yum.repos.d/*.repo /etc/yum.repos.d/backup/"
echo "2. 创建本地源配置文件 /etc/yum.repos.d/local-http.repo，内容如下："
echo "--------------------------------------------------------"
echo "[local-base]"
echo "name=Rocky 9 Local Base (HTTP)"
echo "baseurl=http://$SERVER_IP/yum-repo/rocky9/x86_64/base"
echo "gpgcheck=0"
echo "enabled=1"
echo "priority=1"
echo ""
echo "[local-app]"
echo "name=Rocky 9 Local App (HTTP)"
echo "baseurl=http://$SERVER_IP/yum-repo/rocky9/x86_64/app"
echo "gpgcheck=0"
echo "enabled=1"
echo "priority=1"
echo ""
echo "[local-extra]"
echo "name=Rocky 9 Local Extra (HTTP)"
echo "baseurl=http://$SERVER_IP/yum-repo/rocky9/x86_64/extra"
echo "gpgcheck=0"
echo "enabled=1"
echo "priority=1"
echo "--------------------------------------------------------"
echo "3. 客户端执行：dnf clean all && dnf makecache"
echo "4. 测试安装：dnf install -y vim（从本地仓库安装）"
echo -e "========================================\n"